package thread;

import java.util.PrimitiveIterator;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @author: 成金乘
 * @date: 2023/1/5 17:20
 * @description:
 */
//编写代码, 实现定时器案例
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = time;
    }
    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }
    @Override
    public int compareTo(MyTask o) {
        // 小的在前
        return (int) (this.time - o.time);
    }

}

class MyTimer{
    //扫描线程
    private Thread t = null;
    //创建阻塞优先级队列保存任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public MyTimer(){
        t = new Thread(()->{
            while (true){
                try {
                    //取出队首看是否到时间,如果没到时间放回队列
                    synchronized (this){
                        MyTask myTask = queue.take();
                        long conTime = System.currentTimeMillis();
                        if (conTime < myTask.getTime()){
                            //时间没到,放回去
                            queue.put(myTask);

                            this.wait(myTask.getTime()-conTime);
                        }else {
                            myTask.run();
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    //指定参数,第一个为任务内容,第二个为多少毫秒后执行
    public void schedule(Runnable runnable,long after){
        MyTask myTask = new MyTask(runnable,System.currentTimeMillis()+after);
        queue.put(myTask);
        synchronized (this){
            this.notify();
        }
    }

}

public class ThreadDemo11 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务一");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务二");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("任务三");
            }
        },500);
    }
}
